<template>
  <div class="container">
    <div class="content">
      <div style="padding-bottom: 10px">
        <div style="display: inline-block">
          流程名称：
          <el-input
            placeholder="流程名称"
            style="width: 200px"
            size="small"
            v-model="form.flowName"
          ></el-input>
        </div>
        <el-radio-group
          style="margin-left: 30px"
          v-model="form.formType"
          size="small"
        >
          <el-radio-button
            v-for="(type,index) in $store.state.formTypes"
            :key="index"
            :label="type.value"
          >
            {{ type.label }}
          </el-radio-button>
        </el-radio-group>
        <el-button
          style="float: right"
          type="success"
          icon="el-icon-check"
          size="small"
          @click="save"
        >
          保存
        </el-button>
      </div>
      <el-alert
        style="margin-top: 20px"
        center
        :closable="false"
        v-if="!form.tasks.length"
        type="warning"
        show-icon
      >
        请先选择流程摸板
      </el-alert>
      <template v-else>
        <DefaultFlow
          v-model="form.tasks"
        />
        <div style="text-align: right">
          <el-button
            @click="addTask"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
  import DefaultFlow from './flow/DefaultFlow'

  const fillTemplate = {
    actionUserId: '',
    actionUserName: '',
    collaborator: [] // 合作人
  }
  export default {
    name: 'AddFlow',
    components: { DefaultFlow },
    data () {
      return {
        form: {
          formType: this.$store.state.formTypes[0] ? this.$store.state.formTypes[0].value : '', // 任务名称
          flowName: '', // 流程名称
          tasks: [
            {
              actionUsers: [], // 多个
              taskNodeName: '发起人'
            },
            {
              ...fillTemplate,
              taskNodeName: ''
            }
          ]
        }
      }
    },
    async created () {
      if (this.$route.params.id) {
        const { data } = await this.$service.gzl.getFlow(this.$route.params.id)
        this.form.flowName = data.data.flowName
        this.form.templateId = data.data.templateId
        this.form.formType = data.data.formType
        this.form.tasks = ((items) => {
          const nodeIds = Array.from(new Set(items.map(item => item.taskNodeValue)))
          return nodeIds.map(nodeId => {
            const filters = items.filter(f => f.taskNodeValue === nodeId)
            if (filters.length === 1 && nodeId !== 100) {
              return { ...filters[0], collaborator: JSON.parse(filters[0]['collaborator']) }
            }
            return {
              ...filters[0],
              ...fillTemplate,
              actionUsers: filters.map(item => {
                const { actionUserId, actionUserName } = item
                return { actionUserId, actionUserName }
              })
            }
          })
        })(data.data.tasks)
      }
    },
    methods: {
      addTask () {
        this.form.tasks.push({
          ...fillTemplate,
          taskNodeName: '',
          taskNodeValue: 0,
          taskNextNodeValue: 0
        })
      },
      async save () {
        if (!this.form.formType) {
          this.$message.error('请选择表单类型')
          return
        }
        if (!this.form.flowName) {
          this.$message.error('请填写流程名称')
          return
        }
        if (!this.form.tasks.length) {
          this.$message.error('请设置流程')
          return
        }
        this.form.tasks.forEach((item, index) => {
          const { actionUserName, actionUserId, actionUsers, taskNodeName } = item
          if (!taskNodeName) {
            this.$message.error(`第"${index + 1}行数据"没有设置流程名称`)
            throw new Error('break')
          }
          if (actionUsers) {
            if (!actionUsers.length) {
              this.$message.error(`"${taskNodeName}"没有设置执行人`)
              throw new Error('break')
            }
          } else {
            if (!actionUserName || !actionUserId) {
              this.$message.error(`"${taskNodeName}"没有设置执行人`)
              throw new Error('break')
            }
          }
        })
        const params = this.$_util.deepClone(this.form)
        params.tasks = params.tasks
          .map((item, index) => {
            return {
              ...item,
              taskNodeValue: 100 + index,
              taskNextNodeValue: index === params.tasks.length - 1 ? 10000 : 101 + index
            }
          })
          .reduce((container, item) => {
            const { actionUsers = [], ...rest } = item
            if (actionUsers.length) {
              actionUsers.forEach(row => {
                container.push({ ...rest, ...row })
              })
            } else {
              container.push(rest)
            }
            return container
          }, [])
        // 处理协作人json
        params.tasks = params.tasks.map(item => {
          if (item.collaborator) {
            return { ...item, collaborator: JSON.stringify(item.collaborator) }
          }
          return item
        })
        // console.log(params)
        // return
        if (this.$route.params.id) {
          await this.$confirm('修改流程将使所有采用该流程且正在进行中的审批变为失效状态，是否继续？', '保存提醒')
          await this.$service.gzl.editFlow({ id: this.$route.params.id, ...params })
          this.$message.success('流程编辑成功')
        } else {
          await this.$service.gzl.addFlow(params)
          this.$message.success('流程添加成功')
        }
        this.$closeCurrentGoEdit('/approval/FlowList')
      }
    }
  }
</script>

<style scoped>
  .container {
    padding: 20px;
  }

  .content {
    max-width: 950px;
    padding: 20px 0;
  }
</style>
